package cn.edu.hqu.cst.android.hxy.e4;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.content.Context;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button btnBindService, btnUnbindService, btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind = false;

    ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serviceBinder = (MyService.MyServiceBinder) service;
            isServiceBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBind = false;
            serviceBinder = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnBindService = findViewById(R.id.btn_main_activity_bind_service);
        btnUnbindService = findViewById(R.id.btn_main_activity_unbind_service);
        btnGetStatus = findViewById(R.id.btn_main_activity_get_status);
        tvServiceStatus = findViewById(R.id.tv_main_activity_service_status);

        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, MyService.class);
        if (v.getId() == R.id.btn_main_activity_bind_service) {
            if (!isServiceBind) {
                startService(intent); // 显式启动
                bindService(intent, conn, Context.BIND_AUTO_CREATE);
            }
        } else if (v.getId() == R.id.btn_main_activity_get_status) {
            if (isServiceBind && serviceBinder != null) {
                int count = serviceBinder.getCount();
                tvServiceStatus.setText(String.format(getString(R.string.service_status), count));
            }else {tvServiceStatus.setText("Service 未绑定或已销毁");}
        } else if (v.getId() == R.id.btn_main_activity_unbind_service) {
            if (isServiceBind) {
                unbindService(conn);
                stopService(intent); // 停止 Service
                isServiceBind = false;
                serviceBinder = null;
            }
        }
    }
}